/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aptech.mBean;

import com.aptech.entities.TblUser;
import com.aptech.mBean.util.JsfUtil;
import com.aptech.mBean.util.PaginationHelper;
import com.aptech.sBean.TblUserFacade;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.primefaces.context.RequestContext;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Winner
 */
@ManagedBean(name = "userController")
@SessionScoped
public class UserController implements Serializable {

    public static final String User_SESSION_KEY = "UserSession";
    @EJB
    private TblUserFacade tblUserFacade;
    private TblUser current;
    private DataModel items = null;
    private PaginationHelper paginationHelper;
    private int selectedItemIndex;
    private List<TblUser> listUserByID;

    public List<TblUser> listUserByID(int usID) {
        return tblUserFacade.getUserByID(usID);
    }

    /**
     * Creates a new instance of UserController
     */
    public UserController() {
    }

    public TblUser getSelected() {
        if (current == null) {
            current = new TblUser();
            selectedItemIndex = -1;
        }
        return current;
    }

    public void resetPassword(TblUser u) {
        u.setUsAdress("1");
        getFacade().edit(u);
        FacesMessage msg = new FacesMessage("Password of " + u.getUsUserName() + " is reseted", "");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    private TblUserFacade getFacade() {
        return tblUserFacade;
    }

    public PaginationHelper getPaginationHelper() {
        if (paginationHelper == null) {
            paginationHelper = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return paginationHelper;
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPaginationHelper().createPageDataModel();
        }
        return items;
    }

    public String prepareCreate() {
        current = new TblUser();
        selectedItemIndex = -1;
        return "faces/Client/Register.xhtml";
    }

    public String create() {
        try {
            getFacade().create(current);
            //  JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/i18n/Bundle").getString("ProjectCreated"));
            return prepareCreate();
        } catch (Exception e) {
            // JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/i18n/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareList() {
        recreateModel();
        return "UserManagement";
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        paginationHelper = null;
    }

    public void onEdit(RowEditEvent e) {
        FacesMessage msg = new FacesMessage("Edit User", ((TblUser) e.getObject()).getUsName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
        getFacade().edit((TblUser) e.getObject());
    }

    public void onEditCancel(RowEditEvent e) {
        FacesMessage msg = new FacesMessage("Edit User Cancelled", ((TblUser) e.getObject()).getUsName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public String checkCustomerLogin() {
        try {
            RequestContext context = RequestContext.getCurrentInstance();
            FacesMessage msg = null;
            boolean loggedIn = false;
            List<TblUser> list = getFacade().checkLogin(current.getUsUserName(), current.getUsPassword());
            if (list.size() > 0) {
                current = list.get(0);
                JsfUtil.putSession(User_SESSION_KEY, current);
                loggedIn = true;
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", current.getUsUserName());
                return "app-main";
            } else {
                loggedIn = false;
                msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                context.addCallbackParam("loggedIn", loggedIn);
            }

            //  JsfUtil.addErrorMessage(ResourceBundle.getBundle("/i18n/Bundle").getString("LoginFail"));
            return null;



        } catch (Exception e) {
            //  JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/i18n/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String logoutCustomer() {
        try {
            JsfUtil.logoutSession(User_SESSION_KEY);
            FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
            return "Index";

        } catch (Exception e) {
            //JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/i18n/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }


    }

    @FacesConverter(forClass = TblUser.class)
    public static class UserControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UserController controller = (UserController) context.getApplication().getELResolver().
                    getValue(context.getELContext(), null, "userController");
            return controller.tblUserFacade.find(getKey(value));
        }

        @Override
        public String getAsString(FacesContext context, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof TblUser) {
                TblUser o = (TblUser) object;
                return getStringKey(o.getUsID());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + TblUser.class.getName());
            }
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }
    }
}
